package com.quxing.amazon.common;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.quxing.amazon.common.StatusConst.SUCCESS;
import static com.quxing.amazon.common.StatusConst.SUCCESS_CODE;

/**
 * @author zhb
 * @description HttpServletResponse通用响应
 * @date 2020/11/29 14:11
 */
@Slf4j
public class ResponseUtil {

    private ResponseUtil() {

    }

    public static void writeError(HttpServletResponse response, String msg) {
        try {
            response.setContentType(ContentType.JSON.getValue());
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setStatus(SUCCESS_CODE);
            response.getWriter()
                    .write(JSONUtil.toJsonStr(new JSONObject(Result.error(msg), false)));
        } catch (IOException e) {
            log.error("Response写出JSON异常:{}", e);
        }
    }

    public static void writeError(HttpServletResponse response, int code, String msg) {
        try {
            response.setContentType(ContentType.JSON.getValue());
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setStatus(SUCCESS_CODE);
            response.getWriter()
                    .write(JSONUtil.toJsonStr(new JSONObject(Result.of(code, msg, null), false)));
        } catch (IOException e) {
            log.error("Response写出JSON异常:{}", e.getMessage());
        }
    }

    public static void writeSuccess(HttpServletResponse response, Object data) {
        writeSuccess(response, SUCCESS, data);
    }

    public static void writeSuccess(HttpServletResponse response, String msg, Object data) {
        try {
            response.setContentType(ContentType.JSON.getValue());
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setStatus(SUCCESS_CODE);
            response.getWriter()
                    .write(JSONUtil.toJsonStr(new JSONObject(Result.of(SUCCESS_CODE, msg, data), false)));
        } catch (IOException e) {
            log.error("Response写出JSON异常:{}", e.getMessage());
        }
    }
}
